﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using SdmxMl.GenericMetadata;
using SdmxMl.Manager;
using SdmxMl.Common;
using SdmxMl.Helper;

namespace SilcQuest.CSV
{
    /// <summary> Dialog for fetching export selection (CSV) </summary>
    public partial class DlgCsvHistoryParam : Form
    {
        #region Private members

        private SmManager smCati;
        private MetadataSetType metaSetSuivi;
        private bool isHistory;

        #endregion

        #region C'tor

        /// <summary>C'tor </summary>
        /// <param name="sm">Metadata cache</param>
        /// <param name="history">Is export of history or of questions</param>
        public DlgCsvHistoryParam(SmManager sm, bool history)
        {
            InitializeComponent();
            isHistory = history;
            smCati = sm;
            if (smCati == null)
                smCati = ReferenceManager.GetSmContainerImage();

            comboCsvDelimiter.SelectedIndex = 0;
            ucDatePickerFrom.Date = "2007-01-01";
            ucDatePickerTo.Date = DateTime.Now.ToString("yyyy-MM-dd");
            checkedListBox.SelectedIndex = 0;

            // If not history tracing, propose more options for questionnaire
            groupBoxQuestion.Enabled = isHistory == false;
        }
        #endregion

        #region Save event

        private void buttonSave_Click(object sender, EventArgs e)
        {
            ExportCsvSuivi exportCsv = null;
            ExportCsvQuest exportCsvQ = null;

            // If date cleared force max limits
            if (ucDatePickerFrom.Date == string.Empty)
                ucDatePickerFrom.Date = "2007-01-01";
            if (ucDatePickerTo.Date == string.Empty)
                ucDatePickerTo.Date = DateTime.Now.ToString("yyyy-MM-dd");

            if (checkedListBox.CheckedItems.Count == 0)
            {
                MessageBox.Show("No domain selected!", "Caution", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                try
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.DefaultExt = ".csv";
                    sfd.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        using (new CWaitCursor())
                        {
                            char delimiter = comboCsvDelimiter.SelectedIndex == 0 ? ';' : ',';
                            if (isHistory)
                            {
                                // For each selection, retrieve metadataset of suivi
                                exportCsv = new ExportCsvSuivi(smCati, sfd.FileName, delimiter,
                                    Convert.ToDateTime(ucDatePickerFrom.Date),
                                    Convert.ToDateTime(ucDatePickerTo.Date));

                                ExportHistory(exportCsv);
                            }
                            else
                            {
                                exportCsvQ = new ExportCsvQuest(smCati, sfd.FileName, delimiter);
                                ExportSelectedQuest(exportCsvQ);
                            }
                        }
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (exportCsv != null)
                        exportCsv.Close();
                    if (exportCsvQ != null)
                        exportCsvQ.Close();
                }
            }
        }

        private void ExportSelectedQuest(ExportCsvQuest exportCsvQ)
        {
            bool createHeader = true;
            DateTime dtFrom = Convert.ToDateTime(ucDatePickerFrom.Date);
            DateTime dtTo = Convert.ToDateTime(ucDatePickerTo.Date);
            string[] arrLang = GetSelectedLanguagesToGenerate();

            SilcGroupInfo silcGroup = new SilcGroupInfo();
            foreach (string suiviType in checkedListBox.CheckedItems)
            {
                bool isTechnical = suiviType.StartsWith(SilcGroupInfo.TECH_MARKER);
                string id = isTechnical ? silcGroup.GmdStarter + suiviType : silcGroup.PrependMsId(suiviType);

                // For each year in selected rance
                for (int y = dtFrom.Year; y <= dtTo.Year; ++y)
                {

                    metaSetSuivi = smCati.GetArtefact(SdmxArtefactType.MetadataSet, new ArtefactRefBase(id, silcGroup.AgencyId, y.ToString() + ".0"), true) as MetadataSetType;
                    exportCsvQ.WriteQuest(metaSetSuivi, createHeader, arrLang, radioButtonCode.Checked, GetMaxCodes());
                    createHeader = false;
                }
            }
        }

        private int GetMaxCodes()
        {
            int maxCodes = 0;
            if (int.TryParse(numTextBoxMaxCodes.Text, out maxCodes) == false)
                maxCodes = 0;
            return maxCodes;
        }

        private string[] GetSelectedLanguagesToGenerate()
        {
            List<string> list = new List<string>();
            if (checkBox_de.Checked) list.Add("de");
            if (checkBox_fr.Checked) list.Add("fr");
            if (checkBox_it.Checked) list.Add("it");

            // Nothing selected, default to main application current meta language
            if (list.Count == 0)
                list.Add(LangSupport.CurLang);

            return list.ToArray();
        }

        private void ExportHistory(ExportCsvSuivi exportCsv)
        {
            bool createHeader = true;

            SilcGroupInfo silcGroup = new SilcGroupInfo();
            foreach (string suiviType in checkedListBox.CheckedItems)
            {
                string id = silcGroup.GmdStarter + SilcGroupInfo.SUIVI_MARKER + suiviType;
                metaSetSuivi = smCati.GetArtefact(SdmxArtefactType.MetadataSet, new ArtefactRefBase(id, silcGroup.AgencyId, "1.0"), true) as MetadataSetType;
                exportCsv.WriteQuestHistory(metaSetSuivi, createHeader);
                createHeader = false;
            }
        }
        #endregion

        #region Select/Unselect event

        private void checkBoxSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            // if all selected, clear if not select all
            bool allChecked = checkedListBox.CheckedItems.Count == checkedListBox.Items.Count;
            for (int i = 0; i < checkedListBox.Items.Count; ++i)
                checkedListBox.SetItemChecked(i, allChecked ? false : true);
        }
        #endregion
    }
}

    

